from db.business_dao import BusinessDao
from db.food_dao import FoodDao
from entities.food import Food

class BusinessView:
    def __init__(self):
        self.business_dao = BusinessDao()
        self.food_dao = FoodDao()

    def show_login(self):
        print("\n===============================")
        print("      商家管理系统登录       ")
        print("===============================")
        
        try:
            business_id = int(input("请输入商家编号："))
            password = input("请输入密码：")
            
            business = self.business_dao.login(business_id, password)
            if business:
                print(f"\n登录成功！欢迎，{business.business_name}！")
                self.show_main_menu(business.business_id)
            else:
                print("\n登录失败！商家编号或密码错误！")
                if input("是否重新登录？(y/n): ").lower() == 'y':
                    self.show_login()
        except ValueError:
            print("商家编号必须是数字！")
            self.show_login()

    def show_main_menu(self, business_id):
        while True:
            print("\n--- 一级菜单（商家管理）---")
            print("1.查看商家信息 2.修改商家信息 3.更新密码 4.所属商品管理 5.退出系统")
            
            try:
                choice = int(input("请输入你的选择："))
                
                if choice == 1:
                    self.view_business_info(business_id)
                elif choice == 2:
                    self.update_business_info(business_id)
                elif choice == 3:
                    self.update_password(business_id)
                elif choice == 4:
                    self.show_food_menu(business_id)
                elif choice == 5:
                    print("退出系统！")
                    break
                else:
                    print("无效的选择！")
            except ValueError:
                print("请输入有效的数字选项！")

    def view_business_info(self, business_id):
        business = self.business_dao.get_by_id(business_id)
        if business:
            print("\n=== 商家信息 ===")
            print(f"商家编号：{business.business_id}")
            print(f"商家名称：{business.business_name}")
            print(f"商家地址：{business.business_address}")
            print(f"商家介绍：{business.business_explain}")
            print(f"起送费：{business.star_price:.2f}")
            print(f"配送费：{business.delivery_price:.2f}")
        else:
            print("商家不存在！")

    def update_business_info(self, business_id):
        business = self.business_dao.get_by_id(business_id)
        if not business:
            print("商家不存在！")
            return

        print("\n当前商家信息：")
        self.view_business_info(business_id)
        
        print("\n=== 修改商家信息 ===")
        business.business_name = self._get_update_input(
            "商家名称", business.business_name)
        business.business_address = self._get_update_input(
            "商家地址", business.business_address)
        business.business_explain = self._get_update_input(
            "商家介绍", business.business_explain)
        
        try:
            business.star_price = float(self._get_update_input(
                "起送费", str(business.star_price)))
            business.delivery_price = float(self._get_update_input(
                "配送费", str(business.delivery_price)))
        except ValueError:
            print("价格必须是数字！")
            return

        affected = self.business_dao.update(business)
        if affected > 0:
            print("修改商家信息成功！")
        else:
            print("修改商家信息失败！")

    def _get_update_input(self, field_name, current_value):
        print(f"当前{field_name}：{current_value}")
        if input(f"是否修改{field_name}？(y/n): ").lower() == 'y':
            return input(f"请输入新的{field_name}：")
        return current_value

    def show_food_menu(self, business_id):
        while True:
            print("\n--- 二级菜单（食品管理）---")
            print("1.查看食品列表 2.新增食品 3.修改食品 4.删除食品 5.返回上级菜单")
            
            try:
                choice = int(input("请输入你的选择："))
                
                if choice == 1:
                    self.list_foods(business_id)
                elif choice == 2:
                    self.add_food(business_id)
                elif choice == 3:
                    self.update_food(business_id)
                elif choice == 4:
                    self.delete_food(business_id)
                elif choice == 5:
                    break
                else:
                    print("无效的选择！")
            except ValueError:
                print("请输入有效的数字选项！")

    def list_foods(self, business_id):
        foods = self.food_dao.list_by_business(business_id)
        print("\n=== 食品列表 ===")
        print(f"{'编号':<8}{'名称':<20}{'介绍':<20}{'价格':<10}")
        for food in foods:
            print(f"{food.food_id:<8}{food.food_name:<20}"
                  f"{food.food_explain[:15]+'...' if food.food_explain else '':<20}"
                  f"{food.food_price:<10.2f}")

    def add_food(self, business_id):
        print("\n=== 新增食品 ===")
        food = Food()
        food.business_id = business_id
        food.food_name = input("请输入食品名称：")
        food.food_explain = input("请输入食品介绍：")
        
        try:
            food.food_price = float(input("请输入食品价格："))
        except ValueError:
            print("价格必须是数字！")
            return

        food_id = self.food_dao.add(food)
        if food_id:
            print(f"新增食品成功！食品编号：{food_id}")
        else:
            print("新增食品失败！")

    def update_food(self, business_id):
        self.list_foods(business_id)
        try:
            food_id = int(input("\n请输入要修改的食品编号："))
        except ValueError:
            print("食品编号必须是数字！")
            return

        # 验证食品属于当前商家
        foods = self.food_dao.list_by_business(business_id)
        if not any(f.food_id == food_id for f in foods):
            print("食品不存在或不属于当前商家！")
            return

        food = Food()
        food.food_id = food_id
        food.business_id = business_id
        food.food_name = input("请输入新的食品名称（直接回车保持原值）：")
        food.food_explain = input("请输入新的食品介绍（直接回车保持原值）：")
        
        price_input = input("请输入新的食品价格（直接回车保持原值）：")
        if price_input:
            try:
                food.food_price = float(price_input)
            except ValueError:
                print("价格必须是数字！")
                return

        affected = self.food_dao.update(food)
        if affected > 0:
            print("修改食品成功！")
        else:
            print("修改食品失败！")

    def delete_food(self, business_id):
        self.list_foods(business_id)
        try:
            food_id = int(input("\n请输入要删除的食品编号："))
        except ValueError:
            print("食品编号必须是数字！")
            return

        # 验证食品属于当前商家
        foods = self.food_dao.list_by_business(business_id)
        if not any(f.food_id == food_id for f in foods):
            print("食品不存在或不属于当前商家！")
            return

        if input("确认要删除吗？(y/n): ").lower() == 'y':
            affected = self.food_dao.delete(food_id)
            if affected > 0:
                print("删除食品成功！")
            else:
                print("删除食品失败！")

    def update_password(self, business_id):
        """更新商家密码功能"""
        print("\n=== 更新密码 ===")
        
        # 获取当前商家信息
        business = self.business_dao.get_by_id(business_id)
        if not business:
            print("商家不存在！")
            return
        
        # 验证旧密码
        old_password = input("请输入当前密码：")
        if old_password != business.password:
            print("当前密码不正确！")
            return
        
        # 获取并验证新密码
        while True:
            new_password = input("请输入新密码：")
            confirm_password = input("请再次输入新密码：")
            
            if new_password != confirm_password:
                print("两次输入的密码不一致，请重新输入！")
                continue
                
            if not new_password:
                print("密码不能为空！")
                continue
                
            if new_password == old_password:
                print("新密码不能与旧密码相同！")
                continue
                
            break
        
        # 更新密码
        business.password = new_password
        try:
            affected = self.business_dao.update(business)
            if affected > 0:
                print("密码更新成功！")
            else:
                print("密码更新失败！")
        except Exception as e:
            print(f"密码更新出错: {e}")